﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.IO;
using PerfAnalyzerLib;

namespace UnitTests
{
	public class GeneratorCsvFile
	{
		/// <summary>
		/// Generate an empty temporary file and return its filename.
		/// </summary>
		/// <returns>Filename of the newly generated temporary file.</returns>
		public static string GenerateEmptyFile()
		{
			string filename = Path.GetTempFileName();
			string newFilename = Path.ChangeExtension(filename, "csv");

			// Check if file already exists, delete it if possible.
			if (File.Exists(newFilename))
			{
				File.Delete(newFilename);
			}

			File.Move(filename, newFilename);
			return newFilename;
		}

		/// <summary>
		/// Generate a temporary file containing the given data.
		/// </summary>
		/// <param name="content">Content to add in the file.</param>
		/// <returns>Filename of the generated file.</returns>
		public static string GenerateFile(IEnumerable<string> content)
		{
			string filename = GenerateEmptyFile();
			File.AppendAllLines(filename, content);
			return filename;
		}

		/// <summary>
		/// Generate a csv file.
		/// </summary>
		/// <param name="counters">List of counters to include in the CSV file.</param>
		/// <param name="generateTimeStamp">Create timestamps in CSV file.</param>
		/// <returns>Filename of the newly created file.</returns>
		public static string GenerateCsvFile(List<Counter> counters, bool generateTimeStamp = true)
		{
			if (counters.Count == 0)
			{
				throw new ArgumentException("Cannot create a csv files with no counters.");
			}

			var tick = DateTime.Now;

			var content = new List<string>();

			// counter names
			string line = string.Empty;

			if (generateTimeStamp)
			{
				line = "timestamp,";
			}

			foreach (var counter in counters)
			{
				line += counter.Info.Fullname + ",";
			}

			line = line.Substring(0, line.Length - 1);
			content.Add(line);
			
			for (int i = 0; i < counters[0].Values.Length; i++)
			{
				line = string.Empty;

				if (generateTimeStamp)
				{
					line = tick.AddSeconds(1).ToString(CultureInfo.InvariantCulture) + ",";
				}

				foreach (var counter in counters)
				{
					line += counter.Values[i] + ",";
				}

				line = line.Substring(0, line.Length - 1);
				content.Add(line);

				tick = tick.AddSeconds(1);
			}

			return GenerateFile(content);
		}
	}
}
